﻿using Hangfire;
using Hangfire.Annotations;
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Text;

namespace SX.Core.HangFire.Extension
{
    public static class AppBuilderExtensions
    {
        /// <summary>
        /// 添加HangFire到管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="serverName"></param>
        /// <param name="pathMatch">访问路径</param>
        /// <returns></returns>
        public static IApplicationBuilder UseHangFire(this IApplicationBuilder app,string serverName="",string pathMatch="/hangfire")
        {
            // 容器载入Scheduler服务
            HangfireServiceProvider.ServiceProvider = app.ApplicationServices;
            // 启动Scheduler服务
            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                //wait all jobs performed when BackgroundJobServer shutdown.
                ShutdownTimeout = TimeSpan.FromMinutes(30),
                //默认20
                WorkerCount = Math.Max(Environment.ProcessorCount, 20),
                ServerName=serverName
            });
            // 启动Job界面UI
            app.UseHangfireDashboard(pathMatch, options: new DashboardOptions()
            {
                // 本地测试可以不添加，linux下必添加
                Authorization = new[] { new CustomAuthorizeFilter() }
            });
            return app;
            ///
            /// 特别注意，linux下运行时，可能存在"timezone": "China Standard Time"找不到的情况
            /// 需进行时区复制 cp /usr/share/zoneinfo/Asia/Shanghai /usr/share/zoneinfo/'China Standard Time'
            ///
        }
    }
}
